package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"time"
)

func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 跳过favicon和健康检查
		if c.Request.URL.Path == "/favicon.ico" || c.Request.URL.Path == "/health" {
			c.Next()
			return
		}

		start := time.Now()

		defer func() {
			if r := recover(); r != nil {
				zap.L().Error("Logger middleware panic",
					zap.Any("recover", r),
					zap.String("path", c.Request.URL.Path))
			}
		}()

		c.Next()

		zap.L().Info("HTTP Request",
			zap.String("method", c.Request.Method),
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("duration", time.Since(start)),
			zap.String("client_ip", c.ClientIP()),
		)
	}
}
